#include <iostream>
#include <stdio.h>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdlib>
#include <string>
#include <cassert>
using namespace std;
#define N 2
#define SIZE 1024
void writer(int wfd)
{

    string s("I am child");
    int self = getpid();
    int number = 0;
    char buffer[SIZE];
    while(true)
    {
        buffer[0] = 0; //字符串清空，只是为了告诉阅读代码的人，我把这个数组当做字符串了
        snprintf(buffer, sizeof(buffer), "%s->%d->%d", s.c_str(), self, number++);
        //cout << buffer << endl;
        write(wfd, buffer, strlen(buffer));//写给父进程
        sleep(1);
    }
}

void reader(int rfd)
{
    char buffer[SIZE];
    int cnt = 0;
    while(true)
    {
        //sleep(10);
        buffer[0] = 0;
        ssize_t s = read(rfd, buffer, sizeof(buffer));
        if(s == 0)
        {
            printf("father read file done!\n");
            break;
        }
        else if(s > 0)
        {
            buffer[s] = 0;
            printf("farther get a message[%d] %s\n", getpid(), buffer);
        }

        if(++cnt > 5)  break;
    }
}
int main()
{
    //创建匿名管道
    int pipefd[N] = {0};
    int n = pipe(pipefd);
    assert(!n);
    //printf("pipefd[0]:%d, pipefd[1]:%d\n", pipefd[0], pipefd[1]);

    pid_t id = fork();
    if(id < 0)  return 1;

    if(id == 0)
    {
        //child
        close(pipefd[0]);
        writer(pipefd[1]);

        close(pipefd[1]);
        exit(0);
    }

    //farther
    close(pipefd[1]);
    reader(pipefd[0]);
    close(pipefd[0]);

    sleep(5);

    //回收子进程
    int status;
    pid_t ret = waitpid(id, &status, 0);
    if(ret < 0)  return 1;
    cout << "wait child success" << ret << "exit code:" << ((status>>8)&0xFF) << "exit signal:" << (status&0x7F) << endl;
    return 0;
}